#This is a file that generate a gap instances solved by cplex

import cplex
import random
import readgap
import os

def getidx(i,j,N):
    return j*N + i + 1

def gengap(filename):
    prob = cplex.Cplex()
    nr, nj, c, a, b = readgap.readgap(filename)
    print nr, nj, b
    prob.objective.set_sense(prob.objective.sense.maximize)
    
    for j in range(nr):
        #Add Variables
        varnames = ["x" + str(getidx(i,j, nj)) for i in range(nj)]
        varcosts = c[j]
        vartypes = ["B"] * nj
        prob.variables.add(obj = varcosts,
                           types = vartypes,
                           names = varnames)

        print j
        kexpr =  [varnames, a[j]]
        prob.linear_constraints.add(lin_expr = [kexpr],
                                    senses = ["L"],
                                    rhs = [ b[j] ] )

    #Populate capacity constraints
    for i in range(nj):
        varnames = ["x" + str(getidx(i,j, nj)) for j in range(nr)]
        kexpr = [varnames, [1]*nr ]
        prob.linear_constraints.add(lin_expr = [kexpr],
                                    senses = ["L"],
                                    rhs = [1])
    return prob

def gengap_batch(dirname):
    for filename in os.listdir(dirname):
        prob = gengap(dirname + filename)
        prob.write("gap" + filename + ".lp")

gengap_batch("./c/")


